package com.efounder.chat.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.efounder.chat.R;
import com.efounder.chat.adapter.ChatRoomAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.Group;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.mobilecomps.contacts.ClearEditText;
import com.efounder.mobilecomps.contacts.HanyuParser;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;


/**
 * 群聊列表的activity
 *
 * @author
 */

@SuppressLint("InflateParams")
public class ChatRoomActivity extends BaseActivity {
    private SwipeMenuListView groupListView;
    protected List<Group> grouplist;
    protected List<Group> tempList;
    protected List<Group> totList;
    private ChatRoomAdapter groupAdapter;
    private TextView tv_total;

    private Group deleteGroup;
    private final String TAG = "ChatRoomActivity";
    private SwipeMenuCreator creator;
    private AsyncTask<Void, Void, List<Group>> asyncTask;

    private ClearEditText mClearEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mychatroom);

        initViews();
        loadData();
        setMenu();
        addClickListener();

    }

    private void setMenu() {
        creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // 删除按钮
                SwipeMenuItem deleteItem = new SwipeMenuItem(ChatRoomActivity.this);
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                deleteItem.setWidth(dp2px(90));
                deleteItem.setTitle(R.string.common_text_exit);
                deleteItem.setTitleSize(18);
                deleteItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(deleteItem);
            }
        };
        // set creator
        groupListView.setMenuCreator(creator);

        //标题
        TextView tvTitle = (TextView) this.findViewById(R.id.tv_title);
        tvTitle.setText(getString(R.string.chat_room_name));
        //加号按钮
        ImageView iv_add = (ImageView) this.findViewById(R.id.iv_add);
        iv_add.setVisibility(View.VISIBLE);
        ImageView iv_search = (ImageView) this.findViewById(R.id.iv_search);
        iv_add.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChatRoomActivity.this, CreatChatRoomActivity.class);
                startActivity(intent);
            }

        });
        iv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    /**
     * 退出，进入群聊
     */
    private void addClickListener() {
        groupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //如果点击第一个和最后一个，取消点击事件
                if (i == grouplist.size() + 1 || i == 0) {
                    return;
                }
                // 进入群聊
                final int position = i - 1;

                Log.i(TAG, "点击的item-position：" + position);
                EnvironmentVariable.setProperty("currentChatUserId", String.valueOf(groupAdapter
                        .getItem(position).getGroupId()));
                Intent intent = new Intent();
                intent.putExtra("id", groupAdapter.getItem(position).getGroupId());
                intent.putExtra("chattype", StructFactory.TO_USER_TYPE_GROUP);
                ChatActivitySkipUtil.startChatActivity(ChatRoomActivity.this, intent);
            }
        });

        groupListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu,
                                           int index) {
//                menu.removeMenuItem(readItem);
                switch (index) {
                    case 0:
                        showLoading(ResStringUtil.getString(R.string.common_text_exiting));
                        try {
                            deleteGroup = groupAdapter.getItem(position);

                            GetHttpUtil.userQuitGroup(ChatRoomActivity.this,
                                    groupAdapter
                                            .getItem(position).getGroupId(), new GetHttpUtil.ReqCallBack() {
                                        @Override
                                        public void onReqSuccess(Object result) {
                                            onUserQuitGroupResult(true);
                                        }

                                        @Override
                                        public void onReqFailed(String errorMsg) {
                                            onUserQuitGroupResult(false);

                                        }
                                    });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        break;
                }
                return true;

            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        mClearEditText.setText("");
        loadDataByAsync();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    /**
     * 返回
     *
     * @param view
     */
    @Override
    public void back(View view) {
        finish();
    }


    /**
     * 退群结果
     *
     * @param isSuccess
     */
    public void onUserQuitGroupResult(boolean isSuccess) {
        dismissLoading();
        if (isSuccess) {
            WeChatDBManager.getInstance().quitGroup(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)),
                    deleteGroup.getGroupId());
            grouplist.remove(deleteGroup);
            groupAdapter.notifyDataSetChanged();
            //TODO 删除列表数据
            clearBadgem(deleteGroup.getGroupId(), StructFactory.TO_USER_TYPE_GROUP);

            //生成新的群组名
            //  GroupNameUtil.createNewGroupName(getApplicationContext(),deleteGroup.getGroupId());
            deleteGroup = null;

            tv_total.setText(String.valueOf(grouplist.size()) + getString(R.string.chatroom_num));
            ToastUtil.showToast(ChatRoomActivity.this.getApplicationContext(), ResStringUtil.getString(R.string.chatroom_exit_success));

        } else {
            if (Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)) == deleteGroup.getCreateId()) {
                ToastUtil.showToast(ChatRoomActivity.this.getApplicationContext(), ResStringUtil.getString(R.string.chatroom_exit_cannot_exit));
                return;
            }
        }

    }

    private void clearBadgem(int id, byte chatType) {

        //清除当前聊天的角标
        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(id, chatType);
        int unReadCount = JFMessageManager.getInstance().
                getUnReadCount(id, chatType);
        JFMessageManager.getInstance().unreadZero(id, chatType);

        if (chatListItem != null) {
            WeChatDBManager.getInstance().deleteChatListiItem(chatListItem);
            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.DELETE));
        }
    }


    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }


    //数据库中读取列表数据
    private void loadDataByAsync() {
        asyncTask = new AsyncTask<Void, Void, List<Group>>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showLoading(ResStringUtil.getString(R.string.common_text_loading));
            }

            @Override
            protected List<Group> doInBackground(Void... params) {
                List<Group> groups = WeChatDBManager.getInstance().getallGroupWithOutUsers();

                return groups;
            }

            @Override
            protected void onPostExecute(List<Group> result) {
                super.onPostExecute(result);
                dismissLoading();
                grouplist.clear();
                grouplist.addAll(result);
                totList.clear();
                totList.addAll(grouplist);
                tv_total.setText(String.valueOf(grouplist.size()) + getString(R.string.chatroom_num));
                groupAdapter.notifyDataSetChanged();
            }

            @Override
            protected void onCancelled() {
                super.onCancelled();
                dismissLoading();
            }
        };
        asyncTask.executeOnExecutor(Executors.newCachedThreadPool());

    }


    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        tempList.clear();
        for (int i = 0; i < totList.size(); i++) {
            if (containString(totList.get(i).getGroupName(), filterStr.toLowerCase())) {
                tempList.add(totList.get(i));
            }
        }

        // if (tempList.size() > 0) {
        grouplist.clear();
        grouplist.addAll(tempList);
//        } else {
//            grouplist.clear();
//        }

    }

    private boolean containString(String name, String filterStr) {
        String namePinyin = new HanyuParser().getStringPinYin(name).toLowerCase();
        for (int i = 0; i < filterStr.length(); i++) {
            String singleStr = filterStr.substring(i, i + 1);
            // 汉字
            if (name != null && name.contains(singleStr)) {
                if (i == filterStr.length() - 1) {
                    return true;
                }
                continue;
            }
            // 英文
            if (namePinyin.contains(singleStr)) {
                int currentIndex = namePinyin.indexOf(singleStr);
                namePinyin = namePinyin.substring(currentIndex + 1,
                        namePinyin.length());
            } else {// 不包含
                break;
            }
            if (i == filterStr.length() - 1) {
                return true;
            }
        }
        return false;
    }

    private void initViews() {

        grouplist = new ArrayList<Group>();
        tempList = new ArrayList<Group>();
        totList = new ArrayList<Group>();

        mClearEditText = (ClearEditText) this.findViewById(R.id.filter_edit);
        groupListView = (SwipeMenuListView) findViewById(R.id.groupListView);
        groupListView.setIsNeedIntercept(true);

        // 根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                if (!(s.toString()).equals("")) {
                    filterData(s.toString());
                } else {
                    grouplist.clear();
                    grouplist.addAll(totList);
                }
                groupAdapter.notifyDataSetChanged();
                tv_total.setText(String.valueOf(grouplist.size()) + getString(R.string.chatroom_num));
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) {

                }
            }
        });
        //EditText获取焦点后隐藏掉提示文字
        mClearEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                ClearEditText editText = (ClearEditText) v;
                String hint = null;

                int i = v.getId();
                if (i == R.id.filter_edit) {
                    if (hasFocus) {
                        hint = editText.getHint().toString();
                        editText.setTag(hint);
                        editText.setHint("");
                    } else {
                        hint = editText.getTag().toString();
                        editText.setHint(hint);
                    }

                }
            }
        });
    }

    private void loadData() {
        View headerView = LayoutInflater.from(this).inflate(
                R.layout.item_mychatroom_header, null);
        View footerView = LayoutInflater.from(this).inflate(
                R.layout.item_mychatroom_footer, null);
        tv_total = (TextView) footerView.findViewById(R.id.tv_total);
        tv_total.setText(String.valueOf(grouplist.size()) + getString(R.string.chatroom_num));

        groupAdapter = new ChatRoomAdapter(this, grouplist);
        groupListView.addHeaderView(headerView);
        groupListView.addFooterView(footerView);
        groupListView.setAdapter(groupAdapter);
    }


}
